#include <stdio.h>
#include <strings.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>	//exit()
#include <string.h>     //memset()
#include <mysql++/mysql++.h>
#define PORT 1234
#define MAXSOCKFD 10

int main() {

	int sockfd, newsockfd, is_connected[MAXSOCKFD], fd;
	int i;
	struct sockaddr_in addr;
	int addr_len = sizeof(struct sockaddr_in);
	fd_set readfds;
	char buffer[256];
	char msg[] = "Welcome to server!";

	if ((sockfd = socket(AF_INET,SOCK_STREAM, 0)) < 0) {
		perror("socket");
		exit(1);
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(sockfd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
		perror("connect");
		exit(1);
	}

	if (listen(sockfd, 5) < 0) {
		perror("listen");
		exit(1);
	}

	for (i = 0; i < MAXSOCKFD; i++)
		is_connected[i] = 0;

	is_connected[0] = sockfd;
	while (1) {
		newsockfd = sockfd;
		FD_ZERO(&readfds);
		for (i = 0; i < MAXSOCKFD; i++) {
			if (is_connected[i])
			{
				FD_SET(is_connected[i],&readfds);
				if(newsockfd<is_connected[i]) newsockfd = is_connected[i];
			}
		}
		if (!select(newsockfd+1,&readfds, NULL,NULL, NULL)) {
			continue;
		}
		for (i = 0; i < MAXSOCKFD; i++)
			if (is_connected[i]!=0) {
				if (FD_ISSET(is_connected[i],&readfds)) {

					if (sockfd == is_connected[i]) {
						if ((newsockfd=accept(sockfd, (struct sockaddr*)&addr, (socklen_t*)&addr_len)) < 0)
							perror("accept");
						send(newsockfd, msg, sizeof(msg), 0);
						for (fd = 0; fd < MAXSOCKFD; fd++) {
							if (is_connected[fd] == 0) {
								is_connected[fd] = newsockfd;
							}
						}
						printf("cnnect from %s\n", inet_ntoa(addr.sin_addr));
					} else {
						memset(buffer, 0, sizeof(buffer));
						if (recv(is_connected[i], buffer, sizeof(buffer), 0) <= 0) {
							printf("connect closed %d.\n",is_connected[i]);
							close(is_connected[i]);
							FD_CLR(is_connected[i],&readfds);
							is_connected[i] = 0;
						} else {
							send(is_connected[i], buffer, sizeof(buffer), 0);
							printf("%s", buffer);
						}
					}
				}
			}

	}
	return 0;
}

